package service

import (
	"context"
	"mini-app/internal/app/grpc/client"
	"mini-app/internal/app/grpc/common"
	"mini-app/internal/app/grpc/protoc/devicec"
	"mini-app/internal/app/grpc/protoc/system_admin"
	"mini-app/internal/dal"
	"mini-app/internal/dao"
	"sync"
)

type Robot struct{}

type RobotListT struct {
	RobotID          string `json:"robot_id"`
	ProvinceID       string `json:"-"`
	Province         string `json:"province"`
	CityID           string `json:"-"`
	City             string `json:"city"`
	DistrictID       string `json:"-"`
	District         string `json:"district"`
	LocationID       string `json:"-"`
	Location         string `json:"location"`
	FloorID          string `json:"-"`
	Floor            string `json:"floor"`
	PositionID       string `json:"-"`
	Position         string `json:"position"`           // 精准位置
	Addr             string `json:"addr"`               // 详细地址
	OpeningHours     string `json:"opening_hours"`      // 营业时间
	SaleStatus       int    `json:"sale_status"`        // 售卖状态
	TotalGoods       int64  `json:"total_goods"`        // 设备总商品数
	TotalOnlineGoods int64  `json:"total_online_goods"` // 线上商品
}

// List 门店(机器)列表
func (Robot) List(
	ctx context.Context,
	merchantID string,
	provinceID string,
	cityID string,
	districtID string,
	locationID string,
	robotID string, // 机器编号
	saleStatus int, // 门店状态
	page, limit int, // 分页参数
) (list []RobotListT, total int64, err error) {
	cli, err := client.GetDeviceAdminClient()
	if cli == nil && err != nil {
		return []RobotListT{}, 0, nil
	}
	rsp, _ := common.GRPC{}.DeviceList(
		ctx,
		provinceID, cityID, districtID, locationID,
		merchantID,
		saleStatus,
		robotID,
		page, limit,
	)
	if rsp == nil {
		return []RobotListT{}, 0, nil
	}
	total = rsp.Total
	// 获取全部的设置
	robotIDs := []string{}
	areaIDs := []string{}
	locationIDs := []string{}
	devicePositionIDs := []string{}
	for _, record := range rsp.List {
		robotIDs = append(robotIDs, record.RobotId)
		areaIDs = append(areaIDs, record.ProvinceId, record.CityId, record.DistrictId)
		locationIDs = append(locationIDs, record.LocationId)
		devicePositionIDs = append(devicePositionIDs, record.PositionId)
		list = append(list, RobotListT{
			RobotID:      record.RobotId,
			ProvinceID:   record.ProvinceId,
			CityID:       record.CityId,
			DistrictID:   record.DistrictId,
			LocationID:   record.LocationId,
			Floor:        record.Floor,
			PositionID:   record.PositionId,
			Addr:         record.Addr,
			OpeningHours: record.OpeningHours,
			SaleStatus:   int(record.SaleStatus),
		})
	}
	if len(robotIDs) > 0 {
		// 获取省市区的名称
		{
			cli, err := client.GetSystemAdminClient()
			if err == nil {
				rsp, err := cli.AreaName(context.Background(), &system_admin.AreaNameReq{AreaIds: areaIDs})
				if err == nil && rsp != nil {
					for index, record := range list {
						list[index].Province = rsp.AreaNameMap[record.ProvinceID]
						list[index].City = rsp.AreaNameMap[record.CityID]
						list[index].District = rsp.AreaNameMap[record.DistrictID]
					}
				}
			}
		}
		// 获取位置相关
		{
			cli, err := client.GetAdminClient()
			if cli != nil && err == nil {
				{
					// 获取位置名称
					rsp, err := cli.LocationName(ctx, &devicec.LocationNameReq{
						LocationIds: locationIDs,
					})
					if err == nil && rsp != nil {
						for index, record := range list {
							list[index].Location = rsp.LocationNameMap[record.LocationID]
						}
					}
				}
				{
					// 获取精准位置
					rsp, err := cli.DevicePositionName(ctx, &devicec.DevicePositionNameReq{
						PositionIds: devicePositionIDs,
					})
					if err == nil && rsp != nil {
						for index, record := range list {
							list[index].Position = rsp.DevicePositionNameMap[record.PositionID]
						}
					}
				}

			}
		}
		// 设备商品统计
		{
			var wg sync.WaitGroup
			wg.Add(len(list))
			for index, record := range list {
				go func(index int, record RobotListT) {
					goodsType := 0
					goodsIDs := []string{}
					goodsList, _ := common.GRPC{}.GetGoodsList(ctx, record.RobotID, goodsType, 0, "", "", 1, 0)
					// 初始化新的商品
					for _, record := range goodsList {
						goodsIDs = append(goodsIDs, record.GoodsId)
						if !(dao.GoodsSetting{}).Exists(ctx, dal.Q, robotID, record.GoodsId, "") {
							dao.GoodsSetting{}.Create(ctx, dal.Q, record.GoodsId, robotID, int(record.GoodsType))
						}
					}
					list[index].TotalGoods = int64(len(goodsIDs))
					// 获取商品配置
					// 以零售后台存在的产品为主，所以这里必须以goodsIDs作为过滤
					_, totalOnlineGoods, _ := dao.GoodsSetting{}.List(
						ctx,
						dal.Q,
						record.RobotID,
						goodsIDs,
						"",
						1,
						0, 0,
					)
					list[index].TotalOnlineGoods = totalOnlineGoods
					wg.Done()
				}(index, record)
			}
			wg.Wait()
		}
	}
	return
}
